<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="锁芯片ID" prop="ukeyid">
        <el-input
          v-model="queryParams.ukeyid"
          placeholder="请输入锁芯片ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户" prop="userid">
<!--        <el-input
          v-model="queryParams.userid"
          placeholder="请输入用户ID"
          clearable
          @keyup.enter="handleQuery"
        /> -->
		<el-select v-model="queryParams.userid" placeholder="用户" style="width: 200px;" filterable>
					<el-option
					  v-for="u in users"
					  :key="u.user_id"
					  :label="u.user_name+'('+u.dept_name+')'"
					  :value="u.user_id"
					></el-option>
		</el-select>
      </el-form-item>
<!--      <el-form-item label="ukey加密串  自定义信息加密串" prop="ukeystr">
        <el-input
          v-model="queryParams.ukeystr"
          placeholder="请输入ukey加密串  自定义信息加密串"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['erysys:ukeysysuser:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['erysys:ukeysysuser:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['erysys:ukeysysuser:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['erysys:ukeysysuser:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="ukeysysuserList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="锁芯片ID" align="center" prop="ukeyid" />
      <el-table-column label="用户ID" align="center" prop="userid" >
        <template #default="scope">
	      <!-- <dict-tag :options="users" :value="scope.row.userid"/> -->
		  {{scope.row.username}}
        </template>
      </el-table-column>
	  
      <el-table-column label="ukey加密串  自定义信息加密串" align="center" prop="ukeystr" />
      <el-table-column label="1正常 0停用" align="center" prop="status" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['erysys:ukeysysuser:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['erysys:ukeysysuser:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改用户ukey对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="ukeysysuserRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="锁芯片ID" prop="ukeyid">
          <!-- <el-input v-model="form.ukeyid" placeholder="请输入锁芯片ID" disabled /> -->
		  {{form.ukeyid}}
        </el-form-item>
        <el-form-item label="用户" prop="userid">
          <!-- <el-input v-model="form.userid" placeholder="请输入用户" /> -->
		  <el-select v-model="form.userid" placeholder="用户" filterable>
		  			<el-option
		  			  v-for="u in users"
		  			  :key="u.user_id"
		  			  :label="u.user_name+'('+u.dept_name+')'"
		  			  :value="u.user_id"
		  			></el-option>
		  </el-select>
        </el-form-item>
        <el-form-item label="密钥1" prop="my1">
          <el-input v-model="form.my1" placeholder="密钥1" />
        </el-form-item>
        <el-form-item label="密钥2" prop="my2">
          <el-input v-model="form.my2" placeholder="密钥2" />
        </el-form-item>
        <el-form-item label="密钥3" prop="my3">
          <el-input v-model="form.my3" placeholder="密钥3" />
        </el-form-item>
<!--        <el-form-item label="ukey加密串  自定义信息加密串" prop="ukeystr">
          <el-input v-model="form.ukeystr" placeholder="请输入ukey加密串  自定义信息加密串" />
        </el-form-item> -->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Ukeysysuser">
import Syunew6W from '@/plugins/Syunew6W.js'
import { listUkeysysuser, getUkeysysuser, delUkeysysuser, addUkeysysuser, updateUkeysysuser,getUserList,ukeysysuserJM } from "@/api/erysys/ukeysysuser";

const { proxy } = getCurrentInstance();

const ukeysysuserList = ref([]);
const users = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  ukey:{
	  ukeyid:'',//芯片ID
	  ukeystr:'',//
  },
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    ukeyid: null,
    userid: null,
    ukeystr: null,
    status: null
  },
  rules: {
    ukeyid: [
      { required: true, message: "锁芯片ID不能为空", trigger: "blur" }
    ],
    userid: [
      { required: true, message: "用户不能为空", trigger: "blur" }
    ],
    my1: [
      { required: true, message: "密钥1不能为空", trigger: "blur" }
    ],
    my2: [
      { required: true, message: "密钥2不能为空", trigger: "blur" }
    ],
    my3: [
      { required: true, message: "密钥3不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules,ukey } = toRefs(data);

/** 查询用户ukey列表 */
function getList() {
  loading.value = true;
  listUkeysysuser(queryParams.value).then(response => {
    ukeysysuserList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}
function getUsers() {
  loading.value = true;
  getUserList().then(response => {
	  // console.log(response)
	  users.value=response.data;
	  getList();
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    ukeyid: null,
    userid: null,
    ukeystr: null,
    status: null
  };
  proxy.resetForm("ukeysysuserRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  form.value.ukeyid=ukey.value.ukeyid;
  open.value = true;
  title.value = "添加用户ukey";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getUkeysysuser(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改用户ukey";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["ukeysysuserRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
		  console.log(form.value)
		  // ukeysysuserJM()
        // updateUkeysysuser(form.value).then(response => {
        //   proxy.$modal.msgSuccess("修改成功");
        //   open.value = false;
        //   getList();
        // });
		
      } else {
		  console.log(form.value)
		  ukeysysuserJM(form.value).then(response => {
			if(response.code==200&&response.data.res.length==36){
				form.value.ukeystr=response.data.res;
				addUkeysysuser(form.value).then(response2 => {
				  proxy.$modal.msgSuccess("新增成功");
				  open.value = false;
				  getList();
				});
			}else{
				proxy.$modal.msgError("生成加密串失败");
			}
		  });

      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除用户ukey编号为"' + _ids + '"的数据项？').then(function() {
    return delUkeysysuser(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('erysys/ukeysysuser/export', {
    ...queryParams.value
  }, `ukeysysuser_${new Date().getTime()}.xlsx`)
}

getUsers();
/*------------UKEY-----------*/

function load() {
    //如果是IE10及以下浏览器，则跳过不处理
    if (navigator.userAgent.indexOf("MSIE") > 0 && !navigator.userAgent.indexOf("opera") > -1) return;
    try {
        var s_pnp = new Syunew6W();
        s_pnp.Socket_UK.onopen = function() {
        }

        //在使用事件插拨时，注意，一定不要关掉Sockey，否则无法监测事件插拨
        s_pnp.Socket_UK.onmessage = function got_packet(Msg) {
            var PnpData = JSON.parse(Msg.data);
            if (PnpData.type == "PnpEvent")//如果是插拨事件处理消息
            {
                if (PnpData.IsIn) {
                    alert("UKEY已被插入，被插入的锁的路径是：" + PnpData.DevicePath);
                }
                else {
                    alert("UKEY已被拨出，被拨出的锁的路径是：" + PnpData.DevicePath);
                }
            }
        }

        s_pnp.Socket_UK.onclose = function() {

        }
    }
    catch (e) {
        alert(e.name + ": " + e.message);
        return false;
    }
}

var digitArray = new Array('0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f');

function toHex( n ) {

        var result = ''
        var start = true;

        for ( var i=32; i>0; ) {
                i -= 4;
                var digit = ( n >> i ) & 0xf;

                if (!start || digit != 0) {
                        start = false;
                        result += digitArray[digit];
                }
        }

        return ( result == '' ? '0' : result );
}

async function ukeyOperate(){
	let write_pwd1="4F7C0F97",write_pwd2="C519E486";
	let read_pwd1="SZLS1234",read_pwd2="SZLS1234";
	let data;
	var mSoftKey6A=new Syunew6W();//注意，由于USB的操作是异步的，所以所有函数的调用前必须加await !!!!!!!!!
	let DevicePath =await mSoftKey6A.FindPort(1);//'查找是否存在多把加密锁
	if( mSoftKey6A.GetLastError()== 0 )
	{
		window.alert ( "系统上发现有2把及以上的加密锁，请只插入要进行的加密锁。");return false;
	}
	DevicePath =await mSoftKey6A.FindPort(0);//'查找是否存在加密锁
	if( mSoftKey6A.GetLastError()!= 0 )
	{
		window.alert ( "未发现加密锁，请插入加密锁");return false;
	}
	console.log("加密锁路径:"+DevicePath)
	// {
	// //进行初始化,用于将加密锁数据全部初始化为0，只适用于版本号大于或等于9以上的锁
	// //	 ret=s_simnew1.ReSet(DevicePath);
	// 	//	if( ret != 0 )
	// 	//	{ 
	// 	//		console.log( "初始化错误");return false;
	// 	//	}
	// 	//	console.log( "初始化成功");
		
	// }
	// data=923456789;
	// console.log("加密数据:"+data)
	// {
	// 	let OutSimpleData=await mSoftKey6A.sWriteEx_New(parseInt(data),DevicePath);
	// 	if( mSoftKey6A.GetLastError() != 0 )
	// 	{ 
	// 		window.alert ( "sWriteEx错误");return false;
	// 	}
	// 	console.log( "使用普通算法二对数据"+data+"进行加密后的结果是"+OutSimpleData);
	// 	let OutSimpleData2=await mSoftKey6A.sWrite_2Ex_New(parseInt(OutSimpleData),DevicePath);
	// 	if( mSoftKey6A.GetLastError() != 0 )
	// 	{ 
	// 		window.alert ( "sWriteEx错误");return false;
	// 	}
	// 	console.log( "使用普通算法二对数据"+OutSimpleData+"进行解密后的结果是"+OutSimpleData2);
	// }
	// data="yanxinyu闫新宇";
	// console.log("加密数据:"+data)
	// {
	// 	//设置增强算法密钥二
	// 	let mykey = "ABCDEF1234567890ABCDEF1234567890";
	// 	let ret =await   mSoftKey6A.SetCal_New(mykey, DevicePath);
	// 	if (ret != 0) { window.alert("设置增强算法密钥二错误"); return false; }
	// 	console.log("已成功设置了增强算法二密钥 :"+mykey);
	// } 
	
	// {
	// 	//使用增强算法二对字符串进行加密
	// 	let outstring =await   mSoftKey6A.EncString_New(data,  DevicePath);
	// 	if (mSoftKey6A.GetLastError() != 0) { window.alert("加密字符串出现错误"); return false; }
	// 	console.log("已成功使用增强算法二对字符串进行加密，加密后的字符串为：" + outstring);
	// }
	
	
	// {
	// 	//设置写密码
	// 	let ret=await  mSoftKey6A.SetWritePassword("FFFFFFFF","FFFFFFFF",write_pwd1,write_pwd2, DevicePath);
	// 	if( ret != 0 )
	// 	{ 
	// 		// window.alert ( "设置写密码错误");return false;
	// 		console.log( "设置写密码失败"+ret);
	// 	}else{
	// 	console.log( "设置写密码成功"+ret);
	// 	}
	// }
		
	// {
	// 	//再设置读密码,注意，设置读密码是用原"写"密码进行设置，而不是原“读”密码
	// 	let ret=await  mSoftKey6A.SetReadPassword(write_pwd1,write_pwd2,read_pwd1,read_pwd2, DevicePath);
	// 	if( ret != 0 )
	// 	{ 
	// 		console.log( "设置读密码错误");return  false;
	// 	}else{
	// 		console.log( "设置读密码成功");
	// 	}
 //   }
	
	// //写入字符串带长度
	// {
	// 	//写入字符串带长度，,使用默认的读密码
	// 	let InString = "加密锁闫新宇加密锁123456789";
		
	// 	//写入字符串到地址1
	// 	let nlen =await  mSoftKey6A.YWriteString( InString,1, write_pwd1, write_pwd2, DevicePath);
	// 	if( mSoftKey6A.GetLastError() !=0 )
	// 	{
	// 		console.log("写入字符串(带长度)错误。") ;return  false;
	// 	}
	// 	var LenBuf=new  Uint8Array(1)
	// 	//写入字符串的长度到地址0
	// 	LenBuf[0]=nlen;
	// 	let ret =await  mSoftKey6A.YWrite( LenBuf,0, 1,write_pwd1, write_pwd2, DevicePath);
	// 	if( ret != 0 )
	// 	{
	// 		console.log("写入字符串长度错误。错误码："  +ret.toString());return false;
	// 	}
	// 	console.log("写入字符串(带长度)成功");
	// }
	//读取字符串带长度
	{

		//先从地址0读到以前写入的字符串的长度
		var OutLenBuf =await   mSoftKey6A.YRead(0, 1, read_pwd1,read_pwd2, DevicePath);
		var nlen =OutLenBuf[0];
		// console.log('字符串长度：'+nlen)
		if( mSoftKey6A.GetLastError() !=0 )
		{
			console.log("读取字符串长度错误。错误码：" +mSoftKey6A.GetLastError().toString());return false;
		}
		//再读取相应长度的字符串
		let outString =await   mSoftKey6A.YReadString(1, nlen, read_pwd1,read_pwd2, DevicePath);
		if( mSoftKey6A.GetLastError() != 0 )
			console.log("读取字符串(带长度)错误。错误码："  +mSoftKey6A.GetLastError().toString());
		else
			console.log("已成功读取字符串(带长度)：" + outString);
			
	}
		



	
	
	
	
	
	
	// {
	// 	//用于返回加密狗的版本号
	// 	let version =await  mSoftKey6A.GetVersion(DevicePath);
	// 	if(mSoftKey6A.GetLastError() !=0){ window.alert("返回版本号错误");return false;}
	// 	console.log("已成功返回锁的版本号:"+version);
	// }

	// {
	// 	//用于返回加密狗的版本号
	// 	let version =await  mSoftKey6A.GetVersion(DevicePath);
	// 	if(mSoftKey6A.GetLastError() !=0){ window.alert("返回版本号错误");return false;}
	// 	console.log("已成功返回锁的版本号:"+version);
	// }
		
	// {
	// 	//用于返回加密狗的扩展版本号
	// 	var versionex =await  mSoftKey6A.GetVersionEx(DevicePath);
	// 	if(mSoftKey6A.GetLastError() !=0){ window.alert("返回扩展版本号错误");return false;}
	// 	console.log("已成功返回锁的扩展版本号:"+versionex);
	// }
	// {
	// //'读取锁的ID
	// 	var keyid=toHex(await mSoftKey6A.GetID_1(DevicePath))+toHex(await mSoftKey6A.GetID_2(DevicePath));
	// 	if( mSoftKey6A.GetLastError()!= 0 )
	// 	{
	// 			window.alert( "获取ID错误,错误码是"+mSoftKey6A.GetLastError().toString());
	// 		return false;
	// 	}
	// 	console.log( "锁ID是："+keyid);
	// }
	{
	//'读取锁的芯片ID
		var keyid=await mSoftKey6A.GetChipID(DevicePath);
		if( mSoftKey6A.GetLastError()!= 0 )
		{
				window.alert( "获取ID错误,错误码是"+mSoftKey6A.GetLastError().toString());
			return false;
		}
		ukey.value.ukeyid=keyid
		console.log( "锁芯片ID是："+keyid);
	}
	// //读取MAC地址
	// {
	//     var macAddr =await   mSoftKey6A.MacAddr();
	//     console.log("电脑的MAC地址是：" + macAddr);
	// }
	// //获取电脑名
	// {
	//     var ComputerName =await   mSoftKey6A.ComputerName();
	//     console.log("电脑名是：" + ComputerName);
	// }
	
}
load();
ukeyOperate();
</script>
